package com.yanqu.road.server.cmd.activity.shuihu;

import com.yanqu.road.entity.activity.shuihu.ShuiHuUserData;
import com.yanqu.road.pb.activity.ShuiHuActivityProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.shuihu.ShuiHuModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.shuihu.ShuiHuMgr;
import com.yanqu.road.server.pb.ShuiHuPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

@Cmd(code = GameProtocol.S_SHUIHU_ACTIVITY_COMPOSE, desc = "合成/分解卡片")
public class ShuiHuComposeCmd extends AbstractCommand {

    private int cardId;
    private int count;
    private boolean isCompose;

    private ShuiHuUserData userData;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        ShuiHuActivityProto.ComposeCardReqMsg reqMsg = ShuiHuActivityProto.ComposeCardReqMsg.parseFrom(packet.getBytes());
        cardId = reqMsg.getCardId();
        count = reqMsg.getCount();
        isCompose = reqMsg.getIsCompose();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if (!ActivityMgr.activityInShowTime(ShuiHuMgr.getActivityInfo())) {
            ret = GameErrorCode.E_SHUIHU_ACTIVITY_NO_OPEN;
            return;
        }

        ShuiHuModule shuiHuModule = player.getModule(ShuiHuModule.class);
        userData = shuiHuModule.getUserData();
        if (userData == null) {
            ret = GameErrorCode.E_SHUIHU_ACTIVITY_NO_UNLOCK;
            return;
        }

        if (count <= 0) {
            ret = GameErrorCode.E_SHUIHU_ACTIVITY_COUNT_ERROR;
            return;
        }

        // 合成/分解
        if (isCompose) {
            ret = shuiHuModule.composeCard(cardId, count);
        } else {
            ret = shuiHuModule.decomposeCard(cardId, count);
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        ShuiHuActivityProto.ComposeCardRespMsg.Builder builder = ShuiHuActivityProto.ComposeCardRespMsg.newBuilder();
        builder.setRet(ret);
        if (userData != null) {
            builder.setUserData(ShuiHuPb.parseShuiHuUserDataMsg(userData));
        }
        player.sendPacket(ClientProtocol.U_SHUIHU_ACTIVITY_COMPOSE, builder);
    }
}
